package cn.cdzdjd.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.json.JSONObject;
import org.jsoup.Connection.Response;
import org.springframework.stereotype.Service;

import cn.cdzdjd.exception.ErrorCode;
import cn.cdzdjd.exception.RenException;
import cn.cdzdjd.service.HuYaService;
import cn.cdzdjd.util.JsoupUtil;
import cn.cdzdjd.util.UrlUtil;
import cn.cdzdjd.vo.VideoInfoVO;

@Service
public class HuYaServiceImpl implements HuYaService {
	private final String baseUrl = "https://liveapi.huya.com/moment/getMomentContent?videoId=";

	@Override
	public VideoInfoVO getVideoInfo(String url) {
		String path = UrlUtil.getPath(url);
		int head = StringUtils.lastOrdinalIndexOf(path, "/", 1);
		int tail = StringUtils.lastOrdinalIndexOf(path, ".", 1);
		String videoId = StringUtils.substring(path, head + 1, tail);
		Response response = JsoupUtil.getUrlResponse(baseUrl + videoId);
		String jsonStr = response.body();
		JSONObject json = new JSONObject(jsonStr);
		if (json.getInt("status") == 200) {
			JSONObject videoInfo = json.getJSONObject("data").getJSONObject("moment").getJSONObject("videoInfo");
			String title = videoInfo.getString("videoTitle");
			String videoCover = videoInfo.getString("videoCover");
			if(StringUtils.isEmpty(videoCover)) {
				throw new RenException("解析失败");
			}
			String posterUrl = videoCover.split("\\?")[0];
			String videoUrl = videoInfo.getJSONArray("definitions").getJSONObject(0).getString("url");
			List<String> videoList = new ArrayList<>();
			videoList.add(UrlUtil.setHttps(videoUrl));
			List<String> posterList = new ArrayList<>();
			posterList.add(UrlUtil.setHttps(posterUrl));
			return new VideoInfoVO(videoList, posterList, title, null);
		} else {
			throw new RenException(ErrorCode.PARSE_ERROR, "解析失败");
		}
	}

}
